package com.lightboat.system.queue;

import com.lightboat.common.constant.QueueConstants;
import com.lightboat.common.constant.RedisConstants;
import com.lightboat.common.core.text.Convert;
import com.lightboat.common.enums.ExpressCompanyEnum;
import com.lightboat.common.exception.ServiceException;
import com.lightboat.system.domain.request.LogisticsShippingRequest;
import com.lightboat.system.service.ICrmOrderService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class DelaySaverService {

    public static DelaySaver<String> orderShipping;

    private final RedissonClient redissonClient;

    private final ICrmOrderService crmOrderService;

    @PostConstruct
    public void init() {

        /**
         * 订单发货
         */
        orderShipping = DelaySaver.create(redissonClient, QueueConstants.ORDER_SHIPPING_QUEUE, QueueConstants.ORDER_SHIPPING_QUEUE, 2);
        orderShipping.updateComsumer((orderId) -> {
            RLock lock = redissonClient.getLock(RedisConstants.ORDER_PREFIX + orderId);
            try {
                log.info("订单发货：{}", orderId);
                if (lock.tryLock(3, 3, TimeUnit.SECONDS)) {
                    LogisticsShippingRequest shippingRequest = new LogisticsShippingRequest();
                    shippingRequest.setOrderId(Convert.toLong(orderId));
                    shippingRequest.setShippingType(1);
                    shippingRequest.setLogisticsPlatformCode(ExpressCompanyEnum.JINGDONGKUAIYUN.getCode());
                    crmOrderService.logisticsShipping(shippingRequest);
                }
            } catch (InterruptedException e) {
                log.error("订单发货异常", e);
                throw new ServiceException(e.getMessage());
            } finally {
                lock.unlock();
            }
        });
        orderShipping.start();
    }

    @PreDestroy
    private void shutdown() {
        orderShipping.shutdown();
    }

}
